package aop.test.advice;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public class SimpleMethodInvocation implements MethodInvocation {
    private final Object target;    //目标对象
    private final Method method;    //调用的方法
    private Object[] arguments;     //方法参数
    private final List<MethodInterceptor> interceptors;
    private int interceptorIndex = -1;

    public SimpleMethodInvocation(Method method, Object target, List<MethodInterceptor> interceptors) {
        this.method = method;
        this.target = target;
        this.interceptors = interceptors;
    }

    @Override
    public Method getMethod() {
        return method;
    }

    @Override
    public Object[] getArguments() {
        return arguments;
    }

    @Override
    public Object proceed() throws Throwable {
        //所有拦截器得到执行，调用目标方法
        if(interceptorIndex == this.interceptors.size() - 1){
            return method.invoke(this.target);
        }

        //依次执行每个拦截器
        MethodInterceptor interceptor = this.interceptors.get(++this.interceptorIndex);
        return interceptor.invoke(this);
    }

    @Override
    public Object getThis() {
        return this.target;
    }

    @Override
    public AccessibleObject getStaticPart() {
        return this.method;
    }
}
